package httpclient

import (
	"context"
	"time"

	"gitee.com/git-lz/twelve/common/config"
	"github.com/pkg/errors"
)

var ClientMap = make(map[string]*Client)

type ClientConfig struct {
	Host     string `json:"host"`
	Timeout  int    `json:"timeout"`
	MaxRetry int    `json:"maxRetry"`
}

func Init() {
	clientConfMap := make(map[string]ClientConfig)
	if err := config.Viper.UnmarshalKey("client", &clientConfMap); err != nil {
		panic(err)
	}

	for name, conf := range clientConfMap {
		builder := NewClientBuilder()
		builder.TimeOut(time.Duration(conf.Timeout) * time.Second)
		builder.MaxRetry(conf.MaxRetry)
		builder.BuildResponse(EasyBuildResponse)

		client, err := builder.Build()
		if err != nil {
			panic(err)
		}
		ClientMap[name] = client
	}
}

func GetClient(ctx context.Context, name string) (*Client, error) {
	client, ok := ClientMap[name]
	if !ok {
		return nil, errors.Errorf("client name = (%v) not find", name)
	}

	return client.SetTraceId(ctx), nil
}
